//
//  SMChildRecomendController.swift
//  STMusic
//
//  Created by stoneobs on 17/3/21.
//  Copyright © 2017年 stoneobs. All rights reserved.
//
//**********************推荐的第一个子控制器***************************
import UIKit

class YYChildRecomendController: STTableViewController {

    var adverScrollView:STAdvertingScrollView?;
    
    var adverArray:Array<String>?;
    
    var dataSouce:Array<YYChildRecomendModel> = [];
    
    var isFinshBanerLoad:Bool = false //是否banner加载好
    
    var isFinshTableViewLoad:Bool = false//是否tableView 数据加载好

    
    
    
    var page:Int = 1;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadNetworkRequest();
        self.loadBannerNetRequest();
        self.view.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: self.view.bounds);
        self.tableView.separatorStyle = .none;
        self.tableView.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: self.tableView.bounds);
        self.tableView.frame = .init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 44 - 64);
        self.tableView.allowsSelection = false;
        initSbviews();

        
        _ = YYFMDBManger.shared.cgreateDB(name: "test.db");
        
        //UIViewController;
        // Do any additional setup after loading the view.
    }

   override init!(style: UITableViewStyle) {
        super.init(style: style);
    }


   override init!() {
    super.init();

    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK:privite Method
    func initSbviews() -> Void {
        //bmob 获取

        
        //刷新
        weak var weakSelf = self;
        self.tableView.mj_header = MJChiBaoZiHeader.init(refreshingBlock: {
            weakSelf?.page = 1;
            weakSelf?.dataSouce = [];
            weakSelf?.loadNetworkRequest();
            
        });
        self.tableView.mj_footer = MJChiBaoZiFooter.init(refreshingBlock: {
            weakSelf?.page  = self.page + 1;
            self.isFinshTableViewLoad = true;
            self.isFinshBanerLoad = true;
            weakSelf?.loadNetworkRequest();
        });

        
        
        
        
    }

    // MARK:Network Request
    func loadNetworkRequest() -> Void {
        YYSuiYueNetWorkManger.defultManger.getNetwork(urlString: YYHomePageDefultUrl, dic: ["lang":"utf8","page":self.page], successHandle: { (json) in
            
            print("json = \(json)");
            
            let dataDic:NSDictionary? = json["data"] as? NSDictionary ;
            let array:Array<NSDictionary>! = dataDic?["list"] as! Array<NSDictionary>;
            for i in 0...array!.count - 1{
                if i != 0 {
                    let model = YYChildRecomendModel.mj_object(withKeyValues: array[i]);
                    if (model?.works != nil)  && (model?.user_info != nil &&
                        model?.works.file_long != "") {
                    
                        self.dataSouce.append(model!);
                    }
                    
                    
                }
                
            
            }

            self.tableView.mj_header.endRefreshing();
            self.tableView.mj_footer.endRefreshing();
            self.isFinshTableViewLoad = true;
            if self.isFinshBanerLoad && self.isFinshTableViewLoad {
                self.isFinshTableViewLoad = false;
                self.isFinshBanerLoad = false;
                self.tableView.reloadData();
            }
            
            
        }) { (str) in
            self.tableView.mj_header.endRefreshing();
            self.tableView.mj_footer?.endRefreshing();
        };
    }
    func loadBannerNetRequest(){
    
        //只需要banner 图 
        let urlString = "https://api.suiyueyule.com/1.0.2/feed/new";
        YYSuiYueNetWorkManger.defultManger.addTokenToHeader(token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo0NTY3NDUsImlhdCI6MTQ5MjQ5NzgwOX0.ZAggye9rAw5TagF-KZJ7d-ZZHMfKW8frWV9KIC7DB4M");
        YYSuiYueNetWorkManger.defultManger.getNetwork(urlString: urlString, dic: ["lang":"utf8","page":"1","limit":"20"], successHandle: { (json) in
            
            print("json = \(json)");
            
            let dataDic:NSDictionary? = json["data"] as? NSDictionary ;

            let array:Array<Dictionary<String,Any>> = dataDic!["list"] as! Array;
            
            let banners:Array<Dictionary<String,String>> = array.first!["banner"] as! Array;
            
            var imageUrls:Array<String> = [];
            var models:Array<YYBannerModel> = [];
            for dic in banners{
                
                let str:String = dic["url"]!
                
                let paramStr = str.components(separatedBy: "?").last!;
                let index = paramStr.index(paramStr.startIndex, offsetBy: 7)
                let dicStr:String = paramStr.substring(from: index);
                
                var realstr = dicStr.removingPercentEncoding;
                print("----\(realstr!)")
                realstr = realstr?.replacingOccurrences(of: "{", with: "");
                realstr = realstr?.replacingOccurrences(of: "}", with: "");
                realstr = realstr?.replacingOccurrences(of: "\"", with: "");
                let model:YYBannerModel = YYBannerModel();
                let paramArray:Array<String> = (realstr?.components(separatedBy: ","))!;
                model.url = dic["url"]!;
                model.thumb_img = dic["thumb_img"]!;
                model.type = (paramArray.first?.components(separatedBy: ":").last)!
               
                //nodemusic://web.suiyue?params={"type":"7","share":1,"url":"https://m.suiyueyule.com/template/27   1 碎月详情， 7 web 分享 9 话题详情
                if model.type == "1"{
                    models.append(model);
                    imageUrls.append(dic["thumb_img"]!);
                    model.works_id = (paramArray.last?.components(separatedBy: ":").last)!;
                }
                if model.type == "7"{
                    models.append(model);
                    imageUrls.append(dic["thumb_img"]!);
                    //分享
                    model.openUrl = (paramArray.last?.components(separatedBy: ":").last)!;
                    model.share = (paramArray[1].components(separatedBy: ":").last)!;
                }
                if model.type == "9"{
                    models.append(model);
                    imageUrls.append(dic["thumb_img"]!);
                    //话题
                    model.topic_id = (paramArray[1].components(separatedBy: ":").last)!;
                    model.is_show = 1;
                }


            }
            //header

            
            self.adverScrollView = STAdvertingScrollView.init(frame: .init(x: 7.5, y: 10, width: SCREEN_WIDTH - 15, height: (SCREEN_WIDTH - 15) * 465.0/1243.0), andWith: imageUrls, handle: { (tag) in
                
                let model = models[tag];
                if model.type == "1"{
                    //碎月详情
                    let vc = YYPlayDetailViewController.init(musicID: model.works_id);
                    vc.backgroundImageUrl = model.thumb_img;
                    self.navigationController?.pushViewController(vc, animated: true);
                    
                }else if model.type == "7"{
                    
                    let vc = STWebViewController.init(url: model.openUrl);
                    self.navigationController?.pushViewController(vc!, animated: true);
                }else{
                    
                    let topicModel:YYTopicModel = YYTopicModel();
                    topicModel.id = model.topic_id;
                    let vc = YYTopicDetailViewController.init(topicModel: topicModel)
                    self.navigationController?.pushViewController(vc, animated: true);
                }
                

            });
            self.adverScrollView?.imageUrlsArray = imageUrls;
            self.adverScrollView?.layer.cornerRadius = 5;
            self.adverScrollView?.clipsToBounds = true;
            self.adverScrollView?.canAutoScroll = true;
            let headerView:UIView = UIView.init(frame: .init(x: 0, y: 0, width: SCREEN_WIDTH, height: (SCREEN_WIDTH - 15) * 465.0/1243.0  + 10));
            headerView.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: headerView.bounds);
            headerView.addSubview(self.adverScrollView!);
            self.tableView.tableHeaderView = headerView;
            
            self.isFinshBanerLoad = true;
            if self.isFinshBanerLoad && self.isFinshTableViewLoad {
                self.isFinshTableViewLoad = false;
                self.isFinshBanerLoad = false;
                self.tableView.reloadData();
            }
            
        }) { (str) in

        };
    }
    // MARK: UITableView DataSouce
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSouce.count;
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return YYChildRecomedTableViewCellHeigth;
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 15;
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell:YYChildRecomedTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell") as? YYChildRecomedTableViewCell;
        if cell == nil {
            cell = YYChildRecomedTableViewCell.init(style: .default, reuseIdentifier: "cell");
        }
        if self.dataSouce.count > 0 {
            cell?.model = self.dataSouce[indexPath.row];
        }
  
        weak var weakSelf = self;
        cell?.imageClicHandel = {[weak cell] in
        
            let vc = YYPlayDetailViewController.init(musicID: (self.dataSouce[indexPath.row].works?.id)!)
            vc.backgroundImageUrl = cell?.model.works?.cover_photo;
            vc.type = (cell?.model.works?.type)!;
            weakSelf?.navigationController?.pushViewController(vc, animated: true);
            print("点击了");
        };
        return cell!;
    }
    
    // MARK: UITableView Delegate
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false);
    }

}
